package com.hong.controller;

import com.hong.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Auther: csh
 * @Date: 2019/11/6 11:18
 * @Description:
 */
@Controller
public class UserController {


    /**
     * 测试方式
     */
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        System.out.println("UserController.hello()");
        return "hello";
    }

    @RequestMapping("/add")
    public String add(){
        System.out.println("UserController.add()");
        return "/user/add";
    }


    @RequestMapping("/update")
    public String update(){
        System.out.println("UserController.update()");
        return "/user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        System.out.println("UserController.toLogin()");
        return "login";
    }

    @RequestMapping("/login")
    public String login(String name,String password,Model model){
        /**
         * shiro编写认证的操作
         */
        //1.获取subject操作
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        //3.执行登录方法
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            e.printStackTrace();
            model.addAttribute("msg","用户名不存在！");
            return "login";
            //登录失败
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            model.addAttribute("msg","密码错误!");
            return "login";
        }
        return "test";
    }

    /**
     * 测试thymeleaf
     */
    @RequestMapping("/testThymeleaf")
    public String testThymeleaf(Model model){
        //把数据存入model
        model.addAttribute("name", "test");
        //返回test.html
        return "test";
    }

    @RequestMapping("/unAuth")
    public String unAuth(Model model){
        //把数据存入model
        model.addAttribute("name", "test");
        //返回test.html
        return "unAuth";
    }
}
